/**
 *	---------------------------------------------------------------------------
 *	COMP 6231/FALL 2013
 *	Assignment - 02
 *	@author Talha Rahman (1296884)
 *	---------------------------------------------------------------------------
 *	This class creates a new thread for each UDP requests sent from one server to another
 *	  
 */
package ca.concordia.comp6231.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPClientThread extends Thread{
	
	private String message;
	private String hostName;
	private int serverPort;
	
	private String udpResponseString;

	public UDPClientThread(String message, String hostName, int serverPort){
		this.message = message;
		this.hostName = hostName;
		this.serverPort = serverPort;
	}
	
	@Override
	public void run(){
		udpResponseString = sendUDPMessage();
	}

	public String sendUDPMessage() {
		DatagramSocket aSocket = null;
		String response = "";
		try {
			aSocket = new DatagramSocket();
			byte[] messageInBytes = message.getBytes();
			InetAddress aHost = InetAddress.getByName(hostName);
			DatagramPacket request = new DatagramPacket(
														messageInBytes,
														message.length(), 
														aHost, 
														serverPort
														);
			aSocket.send(request);

			byte[] buffer = new byte[1000];
			DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
			aSocket.receive(reply);

			response = new String(reply.getData());

		} catch (SocketException e) {
			System.out.println("Socket: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO: " + e.getMessage());
		} finally {
			if (aSocket != null)
				aSocket.close();
		}
		
		return response;
	}
	
	public String getUDPResponseString() {
		return udpResponseString;
	}
}
